import { defineStore } from 'pinia';
import {login} from "@/api"

export const useLoginStore = defineStore('login', {
  state: () => {
    const storedUserInfo = localStorage.getItem('userInfo');
    return {
      token: localStorage.getItem('jwtToken') || '',
      userInfo: storedUserInfo ? JSON.parse(storedUserInfo) : null,
      role: localStorage.getItem('userRole') || ''
    }
  },

  actions: {
    login(data){
      login(data).then((res)=>{
        console.log(res);
      })
    },
    setLoginInfo(data) {
      this.token = data.token;
      this.userInfo = data.userInfo;
      this.role = data.role;
      
      // 持久化存储
      localStorage.setItem('jwtToken', data.token);
      localStorage.setItem('userInfo', JSON.stringify(data.userInfo));
      localStorage.setItem('userRole', data.role);
    },
    setUserInfo(userInfo){
      this.userInfo = userInfo;
    },

    clearLoginInfo() {
      this.token = '';
      this.userInfo = null;
      this.role = '';
      
      // 清除所有相关存储
      localStorage.removeItem('jwtToken');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('userRole');
    }
  },

  getters: {
    // 获取token
    getToken: (state) => state.token,
    // 判断是否登录
    isLoggedIn: (state) => !!state.token,
    // 获取用户角色
    getUserRole: (state) => state.role,
    // 获取当前角色ID
    getUserId:(state)=>state.userInfo.data.userId
  }
}); 